package utils

import (
	"context"
	"time"

	"gitee.com/binbin6363/icuc/common/constant"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"golang.org/x/crypto/bcrypt"
)

// EncryptPassword 对密码加密
func EncryptPassword(password string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
	return string(bytes), err
}

// CheckPasswordHash 密码校验
func CheckPasswordHash(password, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	return err == nil
}

// GetUid 从上下文获取uid
func GetUid(ctx context.Context) (uid int64) {
	if c, ok := ctx.(*gin.Context); ok {
		if aUid, ok := c.Get(constant.HeadUid); ok {
			uid = cast.ToInt64(aUid)
			return uid
		}
	}
	return 0
}

// GetUserName 从上下文获取username
func GetUserName(ctx context.Context) (username string) {
	if c, ok := ctx.(*gin.Context); ok {
		if aUserName, ok := c.Get(constant.HeadUserName); ok {
			username = cast.ToString(aUserName)
			return username
		}
	}
	return ""
}

// GetInt64Val 从上下文获取val
func GetInt64Val(ctx context.Context, key string) (val int64) {
	if c, ok := ctx.(*gin.Context); ok {
		if v, ok := c.Get(key); ok {
			val = cast.ToInt64(v)
			return val
		}
	}
	return 0
}

// GetString 从上下文获取val
func GetString(ctx context.Context, key string) (val string) {
	if c, ok := ctx.(*gin.Context); ok {
		if v, ok := c.Get(key); ok {
			val = cast.ToString(v)
			return val
		}
	}
	return ""
}

// QueryInt64Val 从上下文获取val
func QueryInt64Val(ctx context.Context, key string) (val int64) {
	if c, ok := ctx.(*gin.Context); ok {
		val = cast.ToInt64(c.Query(key))
	}
	return val
}

// QueryString 从上下文获取val
func QueryString(ctx context.Context, key string) (val string) {
	if c, ok := ctx.(*gin.Context); ok {
		val = c.Query(key)
	}
	return val
}

// FormatTimeStr 格式化时间戳到字符串
func FormatTimeStr(nowTime int64) string {
	return time.Unix(nowTime, 0).Format("2006-01-02 15:04:05")
}
